package com.example.seckill.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

@Component
public class ValidatorComponent implements InitializingBean {
    private Validator validator;
    @Override
    public void afterPropertiesSet() throws Exception {
        validator= Validation.buildDefaultValidatorFactory().getValidator();
    }

    public ValidateResult validate(Object obj) {
        ValidateResult result = new ValidateResult();
        Set<ConstraintViolation<Object>> set = validator.validate(obj);
        if (set.size() > 0) {
            result.setHasError(true);
            set.forEach(x->{
                String errMsg = x.getMessage();
                String properyName = x.getPropertyPath().toString();
                result.getErrorMap().put(properyName, errMsg);
            });
        }
        return result;

    }
}
